package com.sc.commons.base.utils.except;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sc.commons.base.dto.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.env.Environment;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 切片工具类，用于封装返回值，记录环境变量
 *
 * @author makai@comleader.com.cn
 * @since 0.0.1
 */
@Slf4j
public class AspectUtils {

    /**
     * Spring MVC Controller层日志切片
     * @param pjp
     * @param o
     * @param environment
     * @return
     */
    public static Object controllerAspect(ProceedingJoinPoint pjp, ObjectMapper o, Environment environment) throws Throwable {
        HttpServletRequest request = getRequestByPjp();


        //关联log和数据库中的日志

        String url = request.getRequestURI().toString();
        String queryString = request.getQueryString();

        List<Object> params = new ArrayList<>();
        Method method = getPjpMethod(pjp);

        // 把所有不含Ignore的参数汇在一起
        for (int i = 0; i < method.getParameterAnnotations().length; i++) {
            boolean b = false;
            for (Annotation ann : method.getParameterAnnotations()[i]) {
                if (ControllerAspectIgnore.class.isInstance(ann)) {
                    b = true;
                    break;
                }
            }
            if (!b) {
                params.add(pjp.getArgs()[i]);
            }
        }

        ControllerLog clog = getControllerLog(environment, url, getIp(), o, queryString, params);;


        Object result = null;
        try {
            result = pjp.proceed();
            if (AnnotationUtils.getAnnotation(method, ControllerAspectIgnore.class) == null) {
                BaseResponse b = (BaseResponse) result;
                b.setResCode(200);
                clog.setResult(o.writeValueAsString(result));
            }
            long l = (long) request.getAttribute("mk_starTime");
            clog.setTime(System.currentTimeMillis() - l);
            log.info("mk-log-stack:{}", o.writeValueAsString(clog));
        } catch (Throwable throwable) {
            throw throwable;
        }
        return result;
    }

    public static ControllerLog getControllerLog(Environment environment, String url, String ip, ObjectMapper o, String queryString, List<Object> params) throws JsonProcessingException {
        ControllerLog clog = new ControllerLog();

        clog.setGroupId(environment.getProperty("project.groupId"));
        clog.setArtifactId(environment.getProperty("project.artifactId"));
        clog.setVersion(environment.getProperty("project.version"));
        clog.setAuthor(environment.getProperty("project.author"));

        clog.setLogId(UUID.randomUUID().toString());

        clog.setIp(ip);
        clog.setPort(Integer.parseInt(environment.getProperty("local.server.port")));

        clog.setUrl(url);
        clog.setArgs(o.writeValueAsString(params));
        clog.setQueryString(queryString);
        return clog;
    }

    /**
     * MQ 切片记录接收到的原始数据
     */
    public static void rocketMQAspect(){
        // TODO 已写到MQ服务中，回头再提
    }

    /**
     * 通过PJP，获取Request
     *
     * @return
     */
    private static HttpServletRequest getRequestByPjp() {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        return request;
    }

    /**
     * 获取反映的方法
     *
     * @param pjp
     * @return
     * @throws NoSuchMethodException
     */
    private static Method getPjpMethod(ProceedingJoinPoint pjp) throws NoSuchMethodException {
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        Class<?> clazz = methodSignature.getDeclaringType();
        Method method = clazz.getDeclaredMethod(methodSignature.getName(), methodSignature.getParameterTypes());
        return method;
    }

    /**
     * 建议项目启动的时候初始化IP，懒得改了
     * @return
     */
    private static String getIp() {
        InetAddress localHost = null;
        try {
            localHost = Inet4Address.getLocalHost();
        } catch (UnknownHostException e) {
            log.error(e.getMessage(), e);
        }
        String ip = localHost.getHostAddress();
        return ip;
    }

}
